package com.arch.flink.state;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * 功能描述: 不配置重启策略,默认异常后就失败:
 * 操作步骤:
 *  1. 直接运行程序，当作业打印出10之后，作业退出。
 *  2. 增加env.setRestartStrategy(RestartStrategies.noRestart());观察行为和默认一样。
 *
 * @author pizhihui
 * @date 2024-05-28 19:24
 */
public class D1_NoRestart {



    private final static Logger log = LoggerFactory.getLogger(D1_NoRestart.class);

    public static void main(String[] args) throws Exception {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();


        DataStreamSource<Tuple3<String, Integer, Long>> source = env.addSource(new SourceFunction<Tuple3<String, Integer, Long>>() {

            @Override
            public void run(SourceContext<Tuple3<String, Integer, Long>> ctx) throws Exception {
                int index = 1;
                while (true) {
                    ctx.collect(Tuple3.of("key", index++, System.currentTimeMillis()));
                    Thread.sleep(1000);
                }
            }

            @Override
            public void cancel() {

            }
        });

        source.map(new MapFunction<Tuple3<String, Integer, Long>, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(Tuple3<String, Integer, Long> event) throws Exception {
                if (event.f1 % 10 == 0) {
                    String msg = String.format("Bad data [%d] ...", event.f1);
                    log.error(msg);
                    throw new RuntimeException(msg);
                }
                return Tuple2.of(event.f0, event.f1);

            }
        }).print();


        env.execute("no restart job");

    }

}
